'use strict';
import React from 'react'
import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import NavigationBar from '../../component/navigation/NavigationBar'
import ServicesApi from '../../config/ServicesApi';
import Images from '../../asset';
import ListView from '../../component/list/ListView';
import ImageView from '../../component/common/ImageView';
import Container from "../../component/common/Container";

class MyFollowFans extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {dataSource: []};
        this.page = 1
    }

    doOnCallBack = () => {
        let {onCallBack} = this.params;
        onCallBack && onCallBack();
        RouterHelper.goBack();
    };

    componentDidMount() {
        this.requestDataSources();
    }

    componentWillMount() {
        let {onCallBack} = this.params;
        onCallBack && onCallBack();
    }

    requestDataSources = async () => {
        const {type} = this.props.navigation.state.params;
        let url = '';
        let params = {};
        if (type === Constants.RECOMMEND_TYPE) { //作者推荐
            url = ServicesApi.RECOMMEND_AUTHOR;
            params = {
                search_key: 'rand',
                type: 'recommend',
                focus_user: global.secretKey,
            }
        } else if (type === Constants.FANS_TYPE) { //我的粉丝
            url = ServicesApi.FOCUS_QUERY;
            params = {
                focus_by_user: global.secretKey,
            }
        } else { //我的关注
            url = ServicesApi.FOCUS_QUERY;
            params = {
                focus_user: global.secretKey,
            }
        }
        const limit = 10;
        let data = {
            limit,
            page: this.page,
            ...params,
        };

        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            if (this.page === 1) {
                this.setState({dataSource: result.data})
            } else if (this.page > 1 && result.data.length !== 0) {
                let oldData = this.state.dataSource.slice();
                oldData = oldData.concat(result.data);
                this.setState({dataSource: oldData})
            }
        }
        this._listViewRef && this._listViewRef.stopRefresh();
        this._listViewRef && this._listViewRef.stopEndReached({allLoad: result.data.length < limit})

    };

    _onPressItem = (item, index) => {

    };

    _onRefresh = (stopRefresh) => {
        this.page = 1;
        this.requestDataSources()
    };

    _onEndReached = (stopEndReached) => {
        this.page++;
        this.requestDataSources()
    };

    _onPress = (index) => {
        const {type} = this.props.navigation.state.params;
        const {dataSource} = this.state;
        if (this.checkWatch(dataSource[index])) { //已关注，点击取消关注
            this._cancleFollow(index)
        } else { //未关注，点击关注
            this._follow(index)
        }
    };

    _cancleFollow = async (index) => {
        const {type} = this.props.navigation.state.params;
        const {dataSource} = this.state;
        let url = ServicesApi.FOCUS_DEL;
        let oppositeId;
        if (type === Constants.WATCH_TYPE) {
            oppositeId = dataSource[index].user_by_id;
        } else {
            oppositeId = dataSource[index].user_id;
        }
        let data = {
            focus_user: global.secretKey,
            focus_by_user: oppositeId,
            type: 'field',
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.params.onCallBack && this.params.onCallBack();
            ToastManager.show('取消关注成功');
            this.requestDataSources();
        }
    };

    _follow = async (index) => {
        const {type} = this.props.navigation.state.params;
        const {dataSource} = this.state;
        let url = ServicesApi.FOCUS_SAVE;
        let oppositeId;
        if (type === Constants.WATCH_TYPE) {
            oppositeId = dataSource[index].user_by_id;
        } else {
            oppositeId = dataSource[index].user_id;
        }
        let data = {
            focus_user: global.secretKey,
            focus_by_user: oppositeId,
        };
        const result = await Services.post(url, data);
        // console.log('关注返回---------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.params.onCallBack && this.params.onCallBack();
            ToastManager.show('关注成功');
            this.requestDataSources();
        } else {
            ToastManager.show(result.dec || 'error')
        }
    };

    checkWatch = (item) => {
        // console.log('checkWatch');
        const {type} = this.props.navigation.state.params;
        let isWatch;
        if (type === Constants.WATCH_TYPE) { //关注
            isWatch = true
        } else if (type === Constants.FANS_TYPE) { //粉丝
            isWatch = item.is_attention === '1';
        } else { //推荐作者
            isWatch = !!item.focus_state;
        }
        return isWatch;
    };

    _onPressUserInfo = (author_id) => {
        RouterHelper.navigate('', 'UserCenter', {author_id});
    };

    _renderItem = ({item, index}) => {
        const {type} = this.props.navigation.state.params;
        let img;
        let name;
        let remark;
        let isWatch;
        let author_id;
        if (type === Constants.WATCH_TYPE) { //关注
            img = item.user_by_img ? {uri: item.user_by_img} : Images.icon_default_avatar;
            name = item.user_by_nickname;
            remark = item.user_by_remark;
            author_id = item.user_by_id;
            isWatch = this.checkWatch(item);
        } else { //粉丝，推荐作者
            img = item.user_img ? {uri: item.user_img} : Images.icon_default_avatar;
            name = item.user_nickname;
            remark = item.user_remark;
            remark = item.user_id;
            isWatch = this.checkWatch(item);
        }
        return (
            <TouchableOpacity
                style={styles.itemContainer}
                onPress={() => {
                    this._onPressItem(item, index)
                }}>
                <View style={styles.itemView}>
                    <TouchableOpacity style={styles.followTouch} onPress={() => this._onPressUserInfo(author_id)}>
                        <View style={styles.followTouch}>
                            <ImageView
                                resizeMode={'cover'}
                                style={styles.avatarImage}
                                source={img}
                            />
                            <View style={styles.userinfo}>
                                <Text style={styles.nickname} numberOfLines={1}>{name}</Text>
                                <Text style={styles.signName} numberOfLines={2}>{remark}</Text>
                            </View>
                        </View>
                    </TouchableOpacity>

                    <TouchableOpacity style={styles.rightView} onPress={() => {
                        this._onPress(index)
                    }}>
                        {/* 判断是否关注 */}
                        <Text style={styles.follow}>{isWatch ? '已关注' : '+ 关注'}</Text>
                    </TouchableOpacity>
                </View>
            </TouchableOpacity>
        )
    };

    _keyExtractor = (item, index) => {
        return `item${index}`
    };

    _captureRef = (v) => {
        this._listViewRef = v
    };

    _renderItemSeparator = (info) => {
        return (
            <View style={styles.sep}/>
        )
    };


    render() {
        const {pageTitle} = this.props.navigation.state.params;
        const {dataSource} = this.state;
        return (
            <Container style={styles.container}>
                <NavigationBar
                    title={pageTitle}
                />
                <ListView
                    ref={this._captureRef}
                    initialRefresh={false}
                    enableLoadMore={true}
                    enableRefresh={true}
                    data={dataSource}
                    keyExtractor={this._keyExtractor}
                    renderItem={this._renderItem}
                    ItemSeparatorComponent={this._renderItemSeparator}
                    onRefresh={this._onRefresh}
                    onEndReached={this._onEndReached}
                    ListHeaderComponent={null}
                    style={styles.listView}
                />
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff'
    },
    headerLine: {
        width: Theme.screenWidth,
        height: Theme.minPixel,
        backgroundColor: '#979797',
    },
    listView: {},
    itemContainer: {
        paddingHorizontal: 15,
        paddingVertical: 15,
    },
    itemView: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    avatarImage: {
        width: 50,
        height: 50,
        borderRadius: 25,
    },
    userinfo: {
        marginLeft: 14,
    },
    nickname: {
        fontSize: FontSize(14),
        color: "#585858"
    },
    signName: {
        fontSize: FontSize(10),
        color: "#a2a2a2"
    },
    rightView: {
        borderRadius: 13,
        paddingHorizontal: 9,
        paddingVertical: 5,
        alignItems: 'center',
        borderWidth: Theme.minPixel,
        borderColor: '#ffa64f',
    },
    follow: {
        fontSize: FontSize(10),
        color: '#ffa64f',
    },
    sep: {
        height: Theme.minPixel,
        backgroundColor: '#f5f5f5',
        marginLeft: 15,
        marginRight: 15,
    },
    followTouch: {
        flexDirection: 'row',
        alignItems: 'center',
    },
});

export default MyFollowFans